#include "nim.h"
#include <iostream>
using namespace std;


void GiveInstructions() {
	cout << "Hello.  Welcome to the game of nim."  << endl;
	cout << "In this game, we will start with a pile of" << endl;
	cout << N_COINS  << " coins on the table. " << endl;
	cout << "On each turn, you" << endl;
	cout << "and I will alternately take between 1 and" << endl;
	cout << MAX_TAKEN << " coins from the table." << endl;
	cout << "The player who" << endl;
	cout << "takes the last coin loses." << endl;
	cout << endl;
}

void AnnounceWinner(int nCoins, playT whoseTurn) {
	if (nCoins == 0) {
		cout << "You took the last coin.  You lose." << endl;
	} else {
		cout << "There is only one coin left." << endl;
		switch (whoseTurn) {
  case human:    cout << "I win." << endl; break;
  case computer: cout << "I lose." << endl; break;
		}
	}
}

int GetUserMove(int nCoins) {
	int nTaken, limit;
	while (true) {
		cout << "How many would you like? ";
		cin>>nTaken;
		if (MoveIsLegal(nTaken, nCoins)) break;
		limit = (nCoins < MAX_TAKEN) ? nCoins : MAX_TAKEN;
		cout << "That's cheating!  Please choose a number";
		cout << " between 1 and " << limit << endl;
		cout << "There are " << nCoins << " coins in the pile."<<endl;
	}
	return nTaken;
}

bool MoveIsLegal(int nTaken, int nCoins) {
	return (nTaken > 0 && nTaken <= MAX_TAKEN && nTaken <= nCoins);
}

int ChooseComputerMove(int nCoins) {
	int nTaken = FindGoodMove(nCoins);
	if (nTaken == NO_GOOD_MOVE) nTaken = 1;
	return nTaken;
}

int FindGoodMove(int nCoins) {
	for (int nTaken = 1; nTaken <= MAX_TAKEN; nTaken++) {
		if (IsBadPosition(nCoins - nTaken)) return nTaken;
	}
	return NO_GOOD_MOVE;
}


bool IsBadPosition(int nCoins) {
	if (nCoins == 1) return true;
	return FindGoodMove(nCoins) == NO_GOOD_MOVE;
}

int main() {
	int nCoins, nTaken;
	playT whoseTurn;
	GiveInstructions();
	nCoins = N_COINS;
	whoseTurn = human;
	while (nCoins > 1) {
		cout << "There are " << nCoins << " coins in the pile."<<endl;
		switch (whoseTurn) {
  case human:
	  nTaken = GetUserMove(nCoins);
	  whoseTurn = computer;
	  break;
  case computer:
	  nTaken = ChooseComputerMove(nCoins);
	  cout << "I'll take " << nTaken << "." << endl;
	  whoseTurn = human;
	  break;
		}
		nCoins -= nTaken;
	}
	AnnounceWinner(nCoins, whoseTurn);

	cin.get();
	cin.get();
	return 0;
}